import os
import requests
from flask import Blueprint, request, jsonify
from werkzeug.utils import secure_filename
from pathlib import Path
from openai import OpenAI
from config import UPLOAD_FOLDER, CONVERTED_FOLDER, TO_MD_TYPES, TO_PDF_TYPES, DIRECT_UPLOAD_TYPES

from converters.office_to_pdf import convert_to_pdf
from converters.excel_to_md import convert_to_md

doc_pdf_transform_bp = Blueprint('doc_pdf_transform_bp', __name__, url_prefix='/api/doc')


def upload_to_qwen(file_path):
    try:
        client = OpenAI(
            api_key=os.getenv("DASHSCOPE_API_KEY"),  # 从环境变量获取API密钥,
            base_url=os.getenv("DASHSCOPE_BASE_URL"),
        )
        file_object = client.files.create(
            file=Path(file_path),
            purpose="file-extract"
        )
        return file_object.id, file_object  # 返回ID和完整对象
    except Exception as e:
        print(f"上传千问失败: {str(e)}")
        return None, None


@doc_pdf_transform_bp.route('/transform', methods=['POST'])
def transform_files():
    try:
        data = request.get_json()
        if not data or not isinstance(data, list):
            return jsonify({"code": 2, "error": "无效的请求数据"}), 400

        results = []
        for file_info in data:
            try:
                file_type = file_info.get('fileType', '').lower()
                download_url = file_info.get('downloadUrl', '').strip('`\'" ')

                # 下载文件
                response = requests.get(download_url)
                response.raise_for_status()

                # 保存原始文件
                filename = secure_filename(file_info['displayFilename'])
                os.makedirs(UPLOAD_FOLDER, exist_ok=True)  # 确保目录存在
                input_path = os.path.join(UPLOAD_FOLDER, filename)
                with open(input_path, 'wb') as f:
                    f.write(response.content)

                # 根据文件类型处理
                output_path = None
                if file_type in DIRECT_UPLOAD_TYPES:  # 直接上传的文件类型
                    upload_path = input_path
                elif file_type in TO_PDF_TYPES:  # 需要转PDF的文件类型
                    output_path = convert_to_pdf(input_path, CONVERTED_FOLDER)
                    new_output_path = os.path.join(CONVERTED_FOLDER,
                                                   os.path.splitext(secure_filename(file_info['displayFilename']))[
                                                       0] + '.pdf')
                    os.rename(output_path, new_output_path)
                    output_path = new_output_path
                elif file_type in TO_MD_TYPES:  # 需要转MD的文件类型
                    output_path = convert_to_md(input_path, CONVERTED_FOLDER)
                    new_output_path = os.path.join(CONVERTED_FOLDER,
                                                   os.path.splitext(secure_filename(file_info['displayFilename']))[
                                                       0] + '.md')
                    os.rename(output_path, new_output_path)
                    output_path = new_output_path

                # 确保上传的文件名与 displayFilename 对应
                upload_path = output_path if output_path else input_path
                base_name, ext = os.path.splitext(upload_path)
                new_upload_name = os.path.join(os.path.dirname(upload_path),
                                               os.path.splitext(file_info['displayFilename'])[0] + ext)
                os.rename(upload_path, new_upload_name)

                qwen_file_id, qwen_object = upload_to_qwen(new_upload_name)

                # 上传完成后删除临时文件
                try:
                    if os.path.exists(input_path):
                        os.remove(input_path)
                    if output_path and os.path.exists(output_path):
                        os.remove(output_path)
                    if os.path.exists(new_upload_name):
                        os.remove(new_upload_name)
                except Exception as e:
                    print(f"删除临时文件失败: {str(e)}")
                    # 记录失败
                    pass

                if qwen_object:
                    qwen_object_dict = qwen_object.__dict__
                    qwen_object_dict['fileId'] = file_info.get('id')
                    # 修改filename
                    if file_type in ['doc', 'ppt', 'pptx']:
                        qwen_object_dict['filename'] = os.path.splitext(file_info['displayFilename'])[0] + '.pdf'
                    elif file_type in ['xls']:  # 只对xls文件修改后缀
                        qwen_object_dict['filename'] = os.path.splitext(file_info['displayFilename'])[0] + '.md'
                    else:
                        qwen_object_dict['filename'] = file_info['displayFilename']  # xlsx和docx保持原样
                    results.append(qwen_object_dict)  # 直接返回字典内容
                else:
                    results.append(None)  # 直接返回None

            except Exception as e:
                results.append({
                    "fileId": file_info.get('id'),
                    "error": str(e)
                })

        if any('error' in item for item in results):
            return jsonify({
                "code": 2,
                "data": results,
                "msg": "部分文件处理失败"
            })
        else:
            return jsonify({
                "code": 1,
                "msg": "",
                "data": results
            })

    except Exception as e:
        return jsonify({
            "code": 2,
            "data": [],
            "msg": str(e),
        }), 500
